
import { session } from '../../api/session'
import { pathUtil } from '../../utils/imageUtils'

Page({
  data: {
    isLoggedIn: false,
    user: {
      avatar: '/static/upload/default-avatar.jpg',
      name: '游客',
      signature: '让健康与美味更简单'
    },

    summary: { calories: 0, steps: 0, weight: 0 }
  },

  onLoad() {

  },

  onShow() {
    this.loadUserData()
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      });
    }
  },

  // 加载用户数据
  async loadUserData() {
    const token = wx.getStorageSync('token')
    
    if (token && token !== 'undefined' && token !== 'null') {
      try {
        // 获取用户详细信息
        const sessionRes = await session()
        // 调试
        console.log('sessionRes',sessionRes)

        if (sessionRes && sessionRes.data) {
          const userData = sessionRes.data
          pathUtil
          this.setData({
            isLoggedIn: true,
            user: {
              avatar: pathUtil(userData.yonghuPhoto) || '/static/upload/default-avatar.jpg',
              name: userData.username || '用户',
              signature: userData.signature || '让健康与美味更简单'
            }
          })
          // 本地存储个人主页数据
          wx.setStorageSync('userInfo',{
            userInfo: {
              avatar: pathUtil(userData.yonghuPhoto) || '/static/upload/default-avatar.jpg',
              nickname: userData.username || '游客',
              hasPassword: false,
              phone: userData.yonghuPhone || '',
              signature: '让健康与美味更简单'
            },
          })
        } else {
          throw new Error('Session响应数据格式错误')
        }
      } catch (error) {
        // 如果获取失败，清除本地存储
        wx.removeStorageSync('token')
        wx.removeStorageSync('userid')
        wx.removeStorageSync('role')
        this.setData({
          isLoggedIn: false,
          user: {
            avatar: '/static/upload/default-avatar.jpg',
            name: '游客',
            signature: '让健康与美味更简单'
          }
        })
      }
    } else {
      this.setData({
        isLoggedIn: false,
        user: {
          avatar: '/static/upload/default-avatar.jpg',
          name: '游客',
          signature: '让健康与美味更简单'
        }
      })
    }
    
    // 加载健康数据
    const health = wx.getStorageSync('healthSummary') || { calories: 1680, steps: 7342, weight: 68.2 }
    this.setData({ summary: health })
  },

  login(){
    wx.navigateTo({ url: '/pages/login/login' })
  },

  // 跳转到个人主页
  goToProfile() {
    wx.navigateTo({ url: '/pages/profile/infoCenter/infoCenter' })
  },

  logout(){
    wx.removeStorageSync('token')
    wx.removeStorageSync('userid')
    wx.removeStorageSync('role')
    this.setData({ 
      isLoggedIn: false, 
      user: { 
        avatar: '/assets/images/default-avatar.jpg',
        name: '游客',
        signature: '让健康与美味更简单'
      } 
    })
    wx.showToast({ title: '已退出登录', icon: 'none' })
  },

  // 快捷入口
  goFavorites(){ wx.showToast({ title:'我的收藏（开发中）', icon:'none' }) },
  goRecipes(){ 
    wx.navigateTo({
      url: '/pages/myfood/myfood',
    })
  },
  goHealth(){ wx.navigateTo({ url: '/pages/profile/healthInfo/healthInfo' }) },
  goMessage(){ wx.navigateTo({ url: '/pages/profile/advice/advice' }) },

  // 功能列表
  editProfile(){ wx.navigateTo({ url: '/pages/profile/info/info' }) },
  editWeightMgr(){ wx.navigateTo({ url: '/pages/profile/weightMgr/weightMgr'}) },
  editPreference(){ wx.navigateTo({ url: '/pages/preference/preference' }) },
  ocrReport(){ wx.showToast({ title:'OCR 导入（开发中）', icon:'none' }) },
  feedback(){ wx.showToast({ title:'感谢您的反馈', icon:'none' }) },
  about(){ wx.showModal({ title:'关于', content:'家庭食谱推荐与健康助手', showCancel:false }) }
})